import './index.css'
import Axios from 'axios'
import {Link} from 'react-router-dom'
import bcryptjs from 'bcryptjs'
import React,{useState,useEffect} from 'react'
import { Input, Button,Select,Table, Checkbox, Modal,Tag,Form,message} from 'antd';
const { Option } = Select;
let delData = []
const toList = ['运营人员丶管理员','总经理室','财务会计部','车险营运部','深圳分公司','所有经营机构','改成标准的名字：','信息技术部/大数据中心','客户服务管理部','出单中心','理赔事业部','办公室/风险管理研究中心','盐田支公司','龙岗支公司']
const Accoutmanage = (props)=>{
  const [data,setData] = useState()
  const [visibe,setVisibe] = useState(false)
  const [visibe2,setVisibe2] = useState(false)
  const [rose,setRose] = useState({})
  const [staffsId,setStaffsId] = useState('')
  const [staffsUser,setStaffsUser] = useState('')
  const [staffRose,setStaffRose] = useState('运营人员丶管理员')
  const [newPassValue,setNewPassValue] = useState('')
  const [oldPassValue,setOldPassValue] = useState('')
  useEffect(()=>{
    Axios.get('/staffs').then(response =>{
      const {data} = response
      setData(data)
    })
  },[])
  const columns = [
    {
      title:'',
      key:'value',
      render:(col,row)=>{
        return (
          <Checkbox onChange={(e)=>{
            const {id} = row
            if(e.target.checked){
              delData.push(id)
            }else{
              const idnex = delData.indexOf(id)
              delData.splice(idnex,1)
            }
          }
          }/>
        )
      }
    },
    {
      title:'员工号',
      dataIndex:'staffId'
    },
    {
      title:'姓名',
      dataIndex:'name'
    },
    {
      title:'单位名称',
      dataIndex:'company'
    },
    {
      title:'角色',
      dataIndex:'role'
    },
    {
      title:'数据权限',
      dataIndex:'dataPerm'
    },
    {
      title:'用户状态',
      dataIndex:'pening'
    },
    {
      title:'邮箱',
      dataIndex:'emila'
    },
    {
      title:'手机号',
      dataIndex:'call'
    },
    {
      title:'操作',
      key:'id',
      render:(col,row,index)=>{
        return (
          < >
          <Link to='/accoutmanage/newEdit?disple=true' className="tablespan" onClick={()=>{window.localStorage.setItem('userset',JSON.stringify(row))}}>编辑</Link>

           <span className="tablespan" onClick={()=>{handleAdd(2,row)}}>角色授权</span>
          </>
        )
      }
    }
  ]
  const { getFieldDecorator } = props.form
  return (
    <div className="div">
      <div className="accout">
        <label htmlFor="员工号">员工号:</label>
        <Input
            type="text"
            placeholder="支持模糊搜索"
            style={{ width: '15%', marginRight: '3%',marginLeft:'14px' }}
            value={staffsId}
            onChange={(e)=>{setStaffsId(e.target.value)}}
          />
          <label>岗位名称:</label>
          <Select
            style={{ width: '12%', marginRight: '4%',marginLeft:'14px' }}
            value={staffRose}
            onChange={(e)=>{setStaffRose(e)}}
          >
            {
              toList.map(item => {
                return <Option value={item} key={item}>{item}</Option>
              })
            }
          </Select>
          <label>姓名:</label>
          <Input
              type="text"
              placeholder="支持模糊搜索"
              style={{ width: '15%', marginRight: '3%',marginLeft:'14px' }}
              value={staffsUser}
              onChange={(e)=>{setStaffsUser(e.target.value)}}
            />
            <label>用户状态:</label>
          <Select
            style={{ width: '12%', marginRight: '4%',marginLeft:'14px' }}
            value="rmb"
          >
            <Option value="rmb">正常</Option>
            <Option value="dollar">停用</Option>
          </Select>
          <Button type="danger" onClick={()=>{handleQuery()}}>查询</Button>
        </div>
        <div className="button">
          <Button type="danger" onClick={()=>{handleEdit()}}>新增</Button>
          <Button type="danger" onClick={()=>{handleDel()}}>删除</Button>
          <Button type="danger" onClick={()=>{handleAdd(1)}}>重置密码</Button>
        </div>
        <div className="table">
          <Table
            columns={columns}
            dataSource={data}
            rowKey="id"
            style={{width:'100%'}}
            pagination={{
              pageSize:7
            }}
          />
        </div>
        <Modal
          title="账号管理 > 密码修改"
          visible={visibe}
          onOk={()=>{handleOk(1)}}
          onCancel={()=>{handleCancel(1)}}
          cancelText="取消"
          okText="保存"
          okType="danger"
          bodyStyle={{textAlign:'center',height:'300px',paddingTop:'60px'}}
          width={700}
          mask={false}
        >
          <p>
            <label>原密码</label>
            <Input style={{width:'300px',marginLeft:'15px'}} value={oldPassValue} onChange={(e)=>{setOldPassValue(e.target.value)}}/>
          </p>
            <Form.Item>
            <p className="newpassword">
              <label>新密码</label>
              {
                getFieldDecorator('newpassword',{
                  rules:[
                    { required:true,message:'Please input your newpassword' },
                    {
                      min: 6, message:'最少6位'
                    },
                    {
                      max:12,message:'最多12位'
                    }
                  ]
                })(
                  <Input placeholder="请输入6-12位英文/数字/字符" style={{width:'300px',marginLeft:'15px'}} type="password"/>
                )
                }
              </p>
            </Form.Item>

          <p>
          <label style={{marginRight:'15px'}}>密码确认</label>
            <Input placeholder="请再次输入密码" style={{width:'300px'}} type="password" value={newPassValue} onChange={(e)=>{setNewPassValue(e.target.value)}}/>
          </p>
        </Modal>
        <Modal
          title="角色授权"
          visible={visibe2}
          onOk={()=>{handleOk(2)}}
          onCancel={()=>{handleCancel(2)}}
          cancelText="取消"
          okText="保存"
          okType="danger"
          bodyStyle={{textAlign:'center',height:'280px',paddingTop:'10px'}}
          // width={450}

        >
          <p className="modal-p">
            <span>*</span>
            <label>人员代码</label>
            <Input disabled value={rose.staffId} onChange={()=>{console.log(6)}}/>
          </p>
          <p className="modal-p">
            <span>*</span>
            <label>人员姓名</label>
            <Input disabled value={rose.name} onChange={()=>{console.log(6)}}/>
          </p>
          <p className="modal-p">
            <span style={{color:'red'}}>*</span>
            <label>角色</label>
            <strong>
               <Tag closable  onClose={(e)=>{handleClose(1,rose.role,e)}}>{rose.role}</Tag>
            </strong>

          </p>
        </Modal>
    </div>
  )
  //删除
  function handleDel(){
    const index = [...delData]
    const newData = [...data]
    let newData2 = newData.filter(item => !index.includes(item.id))
    if(index.length === 0){
      message.error('请勾选删除项')
    }else {
      setData(newData2)
      index.forEach(item => {
        Axios.delete(`/staffs/${item}`).then(res => {
          let newIndex = index.filter(data => !data === item)
          delData = newIndex
        })
      })
    }
  }
 //关闭弹窗
  function handleAdd (visibes,row){
    if(visibes === 1){
      setVisibe(true)
    }else {
      setRose(row)
      setVisibe2(true)
    }

  }
   //重置密码
   function handleOk (visibes) {
    let users = JSON.parse(window.localStorage.getItem('users'))[0]
    let password = users.password
    let id = users.id
    if(visibes === 1){
      props.form.validateFields(async(err,values) => {
        if(!err){
          console.log(newPassValue,values)
          if(newPassValue === values.newpassword){
            const isOk = await bcryptjs.compare(oldPassValue,password)
            if (isOk) {
              const newValues = await bcryptjs.hash(values.newpassword,10)
              Axios.patch(`/users/${id}`,{password:newValues}).then(res => {
                users.password = newValues
                let arr = []
                window.localStorage.setItem('users',JSON.stringify([...arr,users]))
              })
            }else{
              message.error('原密码输入错误',1)
            }
          }else{
            message.error('两次输入不一致',1)
          }
        }
      })
      setVisibe(false)
    }else {
      setVisibe2(false)
    }
  }
  function handleCancel(visibes){
    if(visibes === 1){
      setVisibe(false)
    }else {
      setVisibe2(false)
    }
  }
  //新增编辑
  function handleEdit(){
    props.history.push('/accoutmanage/newEdit')
  }
  //查询
  function handleQuery(){
    const newData = data.filter(item=>(()=>{
      if(staffsId) {
        if (staffRose === item.role){
          if (staffsUser){
            return item.name.indexOf(staffsUser) > -1 && item.staffId.indexOf(staffsId)
          }else{
            return item.staffId.indexOf(staffsId) > -1
          }
        }
      }else if(staffsUser){
        if (staffRose === item.role){
          if (staffsId){
            return item.name.indexOf(staffsUser) > -1 && item.staffId.indexOf(staffsId)
          }else{
            return item.name.indexOf(staffsUser) > -1
          }
        }
      }else {
        return  item.role.indexOf(staffRose) > -1
      }
      return item
    }))
    setData(newData)
  }
  //角色删除
  function handleClose (num,str,e) {

    if(num === 1){
      e.preventDefault();
      message.error('只有一位角色，谨慎删除')
      const newRose = {...rose}
      newRose.role = str
      // setRose(newRose)
    }
  }
}

export default Form.create()(Accoutmanage)
